/**
 * Copyright (C) 2007 Mustafa K. Isik - isik@acm.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

package com.paxcodi.sockets.httpget;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class SimpleBrowser {

    /**
     * Requests specified file from specified server on specified port.
     * 
     * @param args URL in format <code>http://host:port/filename</code>
     */
    public static void main(String[] args) {
	String protocolHeader = "http://";
	int remotePort = 80; //default port to connect to
	if(args.length == 0 || !(args[0].startsWith(protocolHeader))){
	    System.err.println("missing or malformed parameter - usage:\n" +
		    "java SimpleBrowser " + protocolHeader + 
		    "host:port/filename\n you may omit the port no in which " +
	    "case the standard http port 80 will be addressed");
	    return;
	}
	//process commandline parameter
	StringBuffer commandlineBuffer = new StringBuffer(args[0]);
	//remove protocolheader from commandline parameter
	commandlineBuffer = 
	    commandlineBuffer.replace(0, protocolHeader.length(), "");
	//get hostname
	int indexOfSlashAfterProtocol = commandlineBuffer.indexOf("/");

	String remoteHost;

	if(commandlineBuffer.indexOf(":") != -1) { //i.e. has been specified

	    int indexOfColon = commandlineBuffer.indexOf(":");
	    remoteHost = commandlineBuffer.substring(0, indexOfColon);
	    //remove host from input
	    commandlineBuffer.replace(0, 
		    indexOfColon + 1, ""); //removes colon too	    
	    //prepare to read port
	    //i.e. adapt indexOfSlashAfterProtocol to reflect deletions
	    indexOfSlashAfterProtocol = 
		indexOfSlashAfterProtocol - indexOfColon - 1;
	    remotePort = Integer.parseInt(
		    commandlineBuffer.substring(0, 
			    indexOfSlashAfterProtocol));	    

	} else {//port had not been specified, use default, 
	    //read host- and filename

	    remoteHost = commandlineBuffer.substring(0, 
		    indexOfSlashAfterProtocol);

	}
	commandlineBuffer = 
	    commandlineBuffer.replace(0, indexOfSlashAfterProtocol + 1,
	    "");//rm slash too
	//read filename of file on webserver
	String filename = commandlineBuffer.toString();
	commandlineBuffer = null; //mark for garbage collection

	try {
	    Socket http = new Socket(remoteHost, remotePort);

	    System.out.println("Connected to " + http.getInetAddress() + 
		    " on port " + http.getPort() + " from local address " + 
		    http.getLocalAddress() + 
		    " via port " + http.getLocalPort());

	    OutputStream routeToRemote = 
		new BufferedOutputStream(http.getOutputStream());
	    OutputStreamWriter writeToRemote = 
		new OutputStreamWriter(routeToRemote, "ASCII");
	    InputStream routeFromRemote = 
		new BufferedInputStream(http.getInputStream());//in bytes
	    InputStreamReader unbufferedReadFromRemote = 
		new InputStreamReader(routeFromRemote); //in characters, unbuff.
	    BufferedReader readFromRemote = 
		new BufferedReader(unbufferedReadFromRemote); //in chars, buff.
	    String msg = "GET /" + filename + " HTTP/1.0\r\n\r\n";
	    //msg = "GET /";
	    writeToRemote.write(msg);
	    writeToRemote.flush();

	    String nextLine = readFromRemote.readLine();

	    while ( !(nextLine == null) ) {
		System.out.println(nextLine);
		nextLine = readFromRemote.readLine();
	    }

	    http.close();	//don't forget to close local port

	} catch (UnknownHostException e) {
	    System.err.println("Cannnot find host: " + remoteHost + "\n" + e);
	} catch (SocketException e){
	    System.err.println("Cannot connect to host: " + 
		    remoteHost + "\n" + e);
	} catch (IOException e) {
	    System.err.println(e);
	    e.printStackTrace();
	}

    }

}